import pandas as pd
import numpy as np
from colorama import Fore, Style, init, AnsiToWin32
import sys
import io

# 初始化colorama，设置strip=False以保留ANSI转义序列
init(strip=False)

# 设置标准输出编码为utf-8，并包装输出以支持ANSI颜色
sys.stdout = AnsiToWin32(sys.stdout)


def calculate_error(predicted, actual):
    """计算误差值"""
    return abs((predicted - actual) / actual * 100)


def check_threshold(error, thresholds):
    """检查误差值是否在阈值范围内"""
    results = []
    for threshold in thresholds:
        if error <= threshold:
            results.append(f"{Fore.GREEN}√{Style.RESET_ALL}")
        else:
            results.append(f"{Fore.RED}x{Style.RESET_ALL}")
    return results


def main():
    # 读取数据
    df = pd.read_csv('merged_output.txt', sep='\t', header=None,
                     names=['frame_name', 'predicted', 'actual'])

    # 设置阈值
    thresholds = [5, 10, 15, 20]

    # 计算误差值
    df['error'] = df.apply(lambda x: calculate_error(x['predicted'], x['actual']), axis=1)

    # 打印表头
    print("\n帧名称\t预测值\t实际值\t误差值\t" + "\t".join([f"{t}%" for t in thresholds]))
    print("-" * 80)

    # 打印每一行的结果
    for _, row in df.iterrows():
        threshold_results = check_threshold(row['error'], thresholds)
        print(f"{row['frame_name']}\t{row['predicted']:.6f}\t{row['actual']:.6f}\t{row['error']:.2f}%\t" +
              "\t".join(threshold_results))

    # 计算各档位的准确率
    print("\n准确率统计：")
    for threshold in thresholds:
        accuracy = (df['error'] <= threshold).mean() * 100
        print(f"误差值 ≤ {threshold}% 的准确率: {accuracy:.2f}%")


if __name__ == "__main__":
    main()
